package com.xunyin.modules.wechatv.rest;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.xunyin.annotation.AnonymousAccess;
import com.xunyin.enums.AppFromEnum;
import com.xunyin.enums.BillDetailEnum;
import com.xunyin.enums.OrderInfoEnum;
import com.xunyin.enums.PayMethodEnum;
import com.xunyin.modules.log.service.mapper.TimelongRecordMapper;
import com.xunyin.modules.membersuser.service.mapper.TMembersUserMapper;
import com.xunyin.modules.mp.config.WxPayConfiguration;
import com.xunyin.modules.mp.service.WeixinPayShareBusService;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.recharge.domain.TRechargeOrder;
import com.xunyin.modules.recharge.service.TRechargeOrderService;
import com.xunyin.modules.shareorder.domain.TShareOrder;
import com.xunyin.modules.shareorder.service.TShareOrderService;
import com.xunyin.modules.shareorder.service.mapper.TShareOrderMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @ClassName WechatvController
 * @Author admin
 * @Date 2022/11/1
 **/
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "微信模块", tags = "微信:微信模块")
public class WechatvController {

    private final TShareOrderService shareOrderService;

    private final TRechargeOrderService rechargeOrderService;

    private final TMembersUserMapper tMembersUserMapper;

    private final TimelongRecordMapper timelongRecordMapper;

    private final TShareOrderMapper tShareOrderMapper;

    private final WeixinPayShareBusService weixinPayShareBusService;

    private final StoreService storeService;

    /**
     * 微信退款回调
     */
    @ApiOperation(value = "退款回调通知处理", notes = "退款回调通知处理")
    @PostMapping("/wechatv/notify/refund")
    public String parseRefundNotifyResult(@RequestBody String xmlData) {
        try {
            WxPayService wxPayService = WxPayConfiguration.getPayService(0, PayMethodEnum.WXAPP);
            WxPayRefundNotifyResult result = wxPayService.parseRefundNotifyResult(xmlData);
            String appOrderNo = result.getReqInfo().getOutTradeNo();
            TShareOrder teaOrder = shareOrderService.selectByAppOrderNo(appOrderNo);
            if ("5".equals(teaOrder.getOrderStatus())) {
                return WxPayNotifyResponse.success("处理成功!");
            }
            Date date = new Date();
            TShareOrder order = new TShareOrder();
            //修改订单状态
            order.setId(teaOrder.getId());
            order.setServiceStatus(5);
            order.setOrderStatus(5);
            //0-未支付；1-已支付；2-支付失败；3-取消
            order.setResultFlag(3);
            //0 未退款 1退款中 2 已到账
            order.setReturnFlag(2);
            //order.setRefundOrderNo(refundNo);
            //order.setRefundTime(DateUtil.parseStrint2Date(successTime, "yyyy-MM-dd HH:mm:ss"));
            order.setRefundTime(new Date());
            // 0-不退款；1-退款中；2-已退款；3-退款失败（微信或支付宝退款失败）
            order.setReturnFlag(2);
            order.setUpdateTime(date);
            tShareOrderMapper.update(order, Wrappers.<TShareOrder>lambdaQuery()
                    .eq(TShareOrder::getId, teaOrder.getId()));

            shareOrderService.refundConpon(teaOrder);

            // 如果有使用优惠券,则把抵扣的优惠券还原未使用状态

            // 如果有使用卡券（小时卡、次数卡）,则还原抵扣（小时卡、次数卡）小时数或次数还原

/*            int i = teaOrder.getDeductTimelong().compareTo(BigDecimal.ZERO);

            if(i>0){
                //返回抵扣的免费时长
                MemberUserVo memberUserVo = tMembersUserMapper.selectByTransPhoneAndMainId(teaOrder.getUserPhone(), teaOrder.getMainId());
                TMembersUser teaMembersUser = new TMembersUser();
                cn.hutool.core.bean.BeanUtil.copyProperties(memberUserVo, teaMembersUser);
                teaMembersUser.setUpdateTime(new Date());
                BigDecimal returnTotalTime = teaMembersUser.getMembersTimeLength().add(teaOrder.getDeductTimelong());
                teaMembersUser.setMembersTimeLength(returnTotalTime);
                tMembersUserMapper.update(teaMembersUser, Wrappers.<TMembersUser>lambdaQuery()
                        .eq(TMembersUser::getId, teaMembersUser.getId()));

                // 记录时长退还日志
                TimelongRecord timelongRecord = new TimelongRecord();
                timelongRecord.setMainId(teaOrder.getMainId());
                timelongRecord.setSource(4);
                timelongRecord.setTimelong(teaOrder.getDeductTimelong());
                timelongRecord.setGiver(0);
                timelongRecord.setRecipient(teaOrder.getMemberUserId());
                timelongRecord.setOrderNo(teaOrder.getOrderNo());
                timelongRecord.setRemark("订单退款-全部使用时长");
                timelongRecord.setCreateUserId(teaOrder.getCreateUserId());
                timelongRecord.setCreateTime(new Date());
                timelongRecord.setStatus(Short.parseShort("1"));
                timelongRecordMapper.insert(timelongRecord);

            }*/

            return WxPayNotifyResponse.success("处理成功!");

        } catch (WxPayException e) {
            log.error(e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }


    /**
     * 微信支付/充值回调
     */
    @AnonymousAccess
    @PostMapping("/wechatv/notify")
    @ApiOperation(value = "微信支付充值回调", notes = "微信支付充值回调")
    public String renotify(@RequestBody String xmlData) {
        try {
            log.info("=====进入回调=====");
            WxPayService wxPayService = WxPayConfiguration.getPayService(0, PayMethodEnum.WXAPP);
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            String appOrderNo = notifyResult.getOutTradeNo();
            String attach = notifyResult.getAttach();
            if (BillDetailEnum.TYPE_3.getValue().equals(attach)) {
                log.info("=====微信支付回调消费订单=====:" + attach);

                log.info("=====微信支付回调消费订单ID=====:" + appOrderNo);
                TShareOrder orderInfo = shareOrderService.selectByAppOrderNo(appOrderNo);
                if (orderInfo == null) {
                    return WxPayNotifyResponse.success("处理成功!");
                }
                if (orderInfo.getOrderStatus().equals(OrderInfoEnum.PAY_STATUS_1.getValue())) {
                    return WxPayNotifyResponse.success("处理成功!");
                }

                orderInfo.setTransactionId(notifyResult.getTransactionId());

                shareOrderService.paySuccess(orderInfo);

                // 分账-当订单实际支付金额大于0，门店设置给平台的抽拥比例大于0时，分账给平台商户
                MtStore mtStore = storeService.queryStoreById(orderInfo.getStoreId());
                BigDecimal zeroBigDecimal = new BigDecimal(0);
                if(mtStore.getOrderCharge() > 0 && orderInfo.getPayMoney().compareTo(zeroBigDecimal) > 0){

                    // 添加分账接收方
                    weixinPayShareBusService.addReceiverMerchant(orderInfo.getStoreId());

                    // 分账
                    weixinPayShareBusService.createProfitSharing(orderInfo, AppFromEnum.WECHAT.getValue(),mtStore.getOrderCharge());
                }


                // 充值
            } else if (BillDetailEnum.TYPE_1.getValue().equals(attach)) {
                //处理充值
                TRechargeOrder stRechargeOrder = rechargeOrderService.selectByAppOrderNo(appOrderNo);
                if (stRechargeOrder == null) {
                    return WxPayNotifyResponse.success("处理成功!");
                }
                if (stRechargeOrder.getOrderStatus().equals(OrderInfoEnum.PAY_STATUS_1.getValue())) {
                    return WxPayNotifyResponse.success("处理成功!");
                }
                stRechargeOrder.setTransactionId(notifyResult.getTransactionId());
                rechargeOrderService.rechargeOrderPayNotify(stRechargeOrder);

            }
            return WxPayNotifyResponse.success("处理成功!");
        } catch (WxPayException e) {
            log.error(e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }

    }

}
